package com.atguigu.gulimall.authserver.controller;

import com.atguigu.common.constant.AuthConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.to.member.MemberRespTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.authserver.feign.MemberFeignService;
import com.atguigu.gulimall.authserver.feign.ThirdPartyFeignService;
import com.atguigu.gulimall.authserver.vo.UserLoginVo;
import com.atguigu.gulimall.authserver.vo.UserResgistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    ThirdPartyFeignService thirdPartyFeignService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthConstant.LOGIN_USER);
        if(attribute==null){
            //未登录，展示登录页
            return "index";
        }else{
            return "redirect:http://gulimall.com";
        }
    }
    @PostMapping("/login")
    public String login(UserLoginVo user, RedirectAttributes model, HttpSession session){
        //远程登录
        MemberRespTo memberRespTo = memberFeignService.login(user);
        if(memberRespTo !=null){
            //TODO 1 作用域问题
            //TODO 2 使用json存放session
            session.setAttribute(AuthConstant.LOGIN_USER, memberRespTo);
            return "redirect:http://gulimall.com";
        }else{
            //校验出错
            Map<String, String> errors =new HashMap<>();
            errors.put("msg","用户名或密码不正确");
            model.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }

    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {
        //TODO 验证码防刷
        String redisCode = stringRedisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            long time = Long.parseLong(redisCode.split("_")[1]);

            if (System.currentTimeMillis() - time < 60000) {
                //短信频繁获取验证码
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        String code = UUID.randomUUID().toString().substring(0, 5);
        String subStr = code+ "_" + System.currentTimeMillis();
        //缓存验证码 十分钟有效
        stringRedisTemplate.opsForValue().set(AuthConstant.SMS_CODE_CACHE_PREFIX + phone, subStr, 10, TimeUnit.MINUTES);
        thirdPartyFeignService.sendCode(phone, code);
        return R.ok();
    }

    /**
     * 模拟重定向携带数据 RedirectAttributes
     * TODO 1. 分布式下的session问题
     *
     * @param user
     * @param result
     * @param model
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserResgistVo user, BindingResult result, RedirectAttributes model) {
        if (result.hasErrors()) {
            //校验出错
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(e -> e.getField(), e -> e.getDefaultMessage()));

            model.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //调用远程服务进行注册
        //1.校验验证码
        String code = user.getCode();
        String codeRedis = stringRedisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + user.getPhone());
        if (!StringUtils.isEmpty(codeRedis)) {
            //验证码不为空
            if (code.equals(codeRedis.split("_")[0])) {
                //校验成功
                //删除验证码，令牌机制
                stringRedisTemplate.delete(AuthConstant.SMS_CODE_CACHE_PREFIX + user.getPhone());
                //调用远程服务进行注册
                R r = memberFeignService.regist(user);
                if(r.getCode()==0){
                    //成功
                    //注册成功，回到首页
                    return "redirect:http://auth.gulimall.com/login.html";
                }else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg","注册失败");
                    model.addFlashAttribute("errors",errors);
                    return  "redirect:http://auth.gulimall.com/reg.html";
                }
            } else {
                //校验不成功
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                model.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            //为空，验证码过期,校验出错
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            model.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

    }
}
